import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/domain/epidemic/epidemic_health_list.dart';
import 'package:flutter_syt/domain/widgets/mine_list_item.dart';
import 'package:flutter_syt/widgets/common_button.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/widgets/common_dialog.dart';
import 'package:flutter_syt/domain/widgets/custom_dialog.dart';
import 'package:flutter_syt/domain/widgets/list_item.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_common.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/starter/http/http_manager.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/web_socket_utility.dart';
import 'package:flutter_syt/widgets/web_protocol.dart';
import 'package:provider/provider.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

@RoutePage(name: "settingPage")
class SettingPage extends StatefulWidget {
  const SettingPage();

  @override
  _SettingPageState createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  @override
  void initState() {
    super.initState();
    loadCache();
  }

  Widget _container(List<ListItemEntity> list) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 0, horizontal: 10.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        color: ThemeColor.bkColorFFFFFF,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: list
            .map((e) => GestureDetector(
                  onTap: ClickUtils.debounce(() => e.onTap),
                  child: Container(
                      // color: Colors.blueGrey,
                      alignment: Alignment.center,
                      child: MineListItem(e)),
                ))
            .toList(),
      ),
    );
  }

  void loadCache() async {
    Directory tempDir = await getTemporaryDirectory();
    double value = await _getTotalSizeOfFileInDir(tempDir);
    print('临时目录大小为： ${value.toString()}');
    print('临时目录大小为： ${_renderSize(value)}');
    setState(() {
      cacheSize = "${_renderSize(value)}";
    });
  }

  _renderSize(double value) {
    List<String> unitArr = ['B', 'K', 'M', 'G'];
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return "${size}${unitArr[index]}";
  }

  Future _getTotalSizeOfFileInDir(final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      final List children = file.listSync();
      double total = 0;
      if (children != null) {
        for (final FileSystemEntity child in children) {
          total += await _getTotalSizeOfFileInDir(child);
        }
      }
      return total;
    }
    return 0;
  }

  Future delDir(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await delDir(child);
      }
    }
    try {
      await file.delete();
    } catch (e) {
      print('删除了基本目录没有权限，暂不处理');
    }
  }

  void clearCache() async {
    Directory tempDir = await getTemporaryDirectory();
    await delDir(tempDir);
    loadCache();
  }

  var cacheSize = '0M';

  @override
  Widget build(BuildContext context) {
    return Consumer<UserInfo>(
      builder: (ctx, info, child) {
        List<ListItemEntity> listData = [
          ListItemEntity(
            S.of(context).clear_cache,
            null,
            cacheSize,
            () => {
              showCommonDialog(
                context,
                DialogEntity(
                  S.of(context).clear_cache_notice,
                  Text(''),
                  () => {Navigator.of(context).pop()},
                  () => {
                    clearCache(),
                    Navigator.of(context).pop(),
                    Future.delayed(Duration(milliseconds: 500), () async {
                      setState(() {});
                    }),
                  },
                  cancelText: S.of(context).cancel,
                  okText: S.of(context).confirm,
                  contentPadding: EdgeInsets.all(0),
                ),
              )
            },
          ),
        ];
        if (info.isLogin) {
          listData.insert(
            0,
            ListItemEntity(
              S.of(context).account_management,
              null,
              '',
              () {
                if (UserInfo.me.registerType == '3' ||
                    UserInfo.me.registerType == '4') {
                  customShowToast(S().login_unBind);
                } else {
                  RouteManager.push(
                    context,
                    RoutMapping.manageAccount(),
                  );
                }
              },
            ),
          );
        }

        List<ListItemEntity> listData2 = [
          ListItemEntity(
            S.of(context).user_agreement,
            null,
            '',
            () {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (ctx) =>
                      WebProtocolDetailPage(GlobalData.userAgreeUrl(context))));
            },
          ),
          ListItemEntity(
            S.of(context).privacy_policy_info,
            null,
            '',
            () {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (ctx) => WebProtocolDetailPage(
                      GlobalData.privacyOverviewUrl(context))));
            },
          ),
          ListItemEntity(
            S.of(context).privacy_policy,
            null,
            '',
            () {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (ctx) =>
                      WebProtocolDetailPage(GlobalData.privacyUrl(context))));
            },
          ),
          ListItemEntity(
            S.of(context).privacy_juvenile,
            null,
            '',
                () {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (ctx) =>
                      WebProtocolDetailPage(GlobalData.privacyJuvenile(context))));
            },
          ),


          ListItemEntity(
            S.of(context).personal_sharing,
            null,
            '',
            () {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (ctx) =>
                      WebProtocolDetailPage(GlobalData.sharingUrl(context))));
            },
          ),
          ListItemEntity(
            S.of(context).personal_collection,
            null,
            '',
            () {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (ctx) => WebProtocolDetailPage(
                      GlobalData.collectionUrl(context))));
            },
          ),
          ListItemEntity(
            S.of(context).version,
            null,
            appContext.packageInfo.version,
            () {
              VersionUpdate.update(context, true);
            },
          ),
          ListItemEntity(
            S.of(context).Version_records,
            null,
            '',
            () {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (ctx) =>
                      WebProtocolDetailPage(GlobalData.upgrade(context))));
            },
          ),
          ListItemEntity(
            S.of(context).about,
            null,
            '',
            () async {
              // loading(() {

              // });
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (ctx) =>
                      WebProtocolDetailPage(GlobalData.aboutme(context))));

              // EasyLoading.instance.flash(() =>)();
              // var data = await API.shared.user.agreements(4);
            },
          ),
        ];
        var content = Scaffold(
          appBar: AppBar(
            title: Text(
              S.of(context).settings,
            ),
          ),
          body: Column(
            children: [
              Expanded(child: SingleChildScrollView(child: Column(children: [
                _container(listData),
                _container(listData2),
              ],),)),
            const  SizedBox(
                height: 12,
              ),
              // Spacer(),
              if (info.isLogin)
                SafeArea(
                  top: false,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                    child: CommonButton(
                      width: 180,
                      title: S().logout,
                      isLine: true,
                      onAsyncClick: () async {
                        try {
                          await GlobalData.unbindPush();

                          WebSocketUtility.instance.closeSocket();
                          // OnlineGlobalData.shared.clean();
                          await API.shared.user.logout();
                          UserInfo.clean();
                          Navigator.of(context)
                              .popUntil((route) => route.isFirst);

                        } catch (e) {

                        }
                      },
                    ),
                    // child: ElevatedButton(
                    //   onPressed: ClickUtils.debounce(
                    //     () async {
                    //       // loading(() async {
                    //
                    //         await GlobalData.unbindPush();
                    //         await API.shared.user.logout();
                    //         WebSocketUtility.instance.closeSocket();
                    //         // OnlineGlobalData.shared.clean();
                    //         UserInfo.clean();
                    //         Navigator.of(context)
                    //             .popUntil((route) => route.isFirst);
                    //       // });
                    //     },
                    //   ),
                    //   child: Text(
                    //     S.of(context).logout,
                    //     style: TextStyle(
                    //       color: Colors.black.withOpacity(0.8),
                    //       fontSize: 16,
                    //       fontWeight: FontWeight.bold,
                    //     ),
                    //   ),
                    // ),
                  ),
                ),
            ],
          ),
        );
        return content;
      },
    );
  }
}
